package com.jckj.core.db.interceptor;

import com.jckj.core.util.MyUtils;
import com.jckj.core.util.SpringContextHolder;
import com.jckj.core.vos.LoginUserVo;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Properties;


/**
 * 数据权限拦截器
 * @author liuzhiyuan
 * @date 2018-01-04
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})
public class DBInterceptor implements Interceptor {

    public static final Logger LOGGER = LoggerFactory.getLogger(DBInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if(1==1){
            return invocation.proceed();
        }
        LoginUserVo user = SpringContextHolder.getBean(LoginUserVo.class);
        Boolean jump = MyUtils.getJumpFlag();
        if(jump!=null&&jump){
            LOGGER.info("跳过数据过滤");
            return invocation.proceed();
        }
//        if(user.isAdmin()||!user.isLogged()){
//            return invocation.proceed();
//        }
        Object obj = invocation.getArgs()[1];
        if(obj.getClass().getName().contains("Example")){
            Class clazz = obj.getClass();
            Field field = clazz.getDeclaredField("oredCriteria");
            field.setAccessible(true);

            String classFullName = obj.getClass().getName() + "$Criteria";

            List<?> oredCriteria = (List<?>)field.get(obj);

            for(Object criteria : oredCriteria){
                Class iClazz = Class.forName(classFullName);
                //iClazz.getMethod("andOfficeIdEqualTo", String.class).invoke(criteria, user.getOfficeId());
                iClazz.getMethod("andCreateByEqualTo", String.class).invoke(criteria, "1");
                //iClazz.getMethod("andOfficeIdEqualTo", String.class).invoke(criteria, user.getOfficeId());
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
